<?php

namespace Service\RpcService\RpcJavaGateWayServer;

use App\Model\PssLogModel\JavaApiLog;
use Service\Code\Normal;
use App\Service\HttpServer\Http;

/**
 * RPC JAVA HTTP GateWay Client Center
 * @author chenshubo
 */
class RpcJavaGateWayHttpClient
{
    protected $gateway_url = null;
    const REQUEST_GET   = 'get';
    const REQUEST_POST  = 'post';
    public function __construct(string $gateway) 
    {
        $this->gateway_url = $gateway;
    }
    
    /**
     * GET 请求
     * @param string $route
     * @param array $data
     * @return mixed
     */
    public function get(string $route, array $data = [])
    {
        return $this->transfer(self::REQUEST_GET,$route,$data);
    }
    
    /**
     * post 请求
     * @param string $route
     * @param array $data
     * @return mixed
     */
    public function post(string $route , array $data = [])
    {
        return $this->transfer(self::REQUEST_POST,$route,$data);
    }
    
    /**
     * 开始请求
     * @param string $method
     * @param string $route
     * @param array $data
     */
    private function transfer(string $method,string $route, array $data)
    {
        $url = $this->gateway_url.$route;
        $method = strtolower($method);
        $start_time = microtime(true);
        
        //请求处理
        if( $method == self::REQUEST_GET ) {
            $query_param = [];
            foreach ($data as $key => $val) {
                $query_param[] = "{$key}={$val}";
            }
            $query_string = implode("&", $query_param);
            $url .= "?".$query_string;
            $response = Http::get($url);
        } else if( $method == self::REQUEST_POST ) {
            $response = Http::postJsonCurl($url, $data);
        } else {
            return Normal::returnCode(Normal::FAIL,"当前传入method【{$method}】不支持");
        }
        
        $used_time = bcsub((string)microtime(true),(string)$start_time,3);
        JavaApiLog::instance()->addLog($method,$url,json_encode($data,JSON_UNESCAPED_UNICODE), $response, $used_time);
        
        $result = @json_decode($response,true,512,JSON_BIGINT_AS_STRING);
        if( isset($result['code']) && $result['code'] == Normal::SUC ) {
            return $result;
        }
        
        $code = isset($result['code']) ? $result['code'] : 0 ;
        return Normal::returnCode($code,"服务中心接口失败【{$response}】");
    }
}